package com.goudan.rabbitmq.support;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Slf4j
@Component
@ConditionalOnProperty(prefix = "spring.rabbitmq", name = "publisher-confirm-type", havingValue = "correlated")
public class MessageConfirmCallBack implements RabbitTemplate.ConfirmCallback {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
    }

    /**
     * 交换机确认回调方法 (发布者发送消息是否到交换机触发回调)
     * 1. 发消息 交换机接收到消息，回调
     * 1.1 correlationData 保存毁掉消息的id及相关信息
     * 1.2 交换机接收到消息 true
     * 1.3 失败原因-null
     * 2. 发消息 交换机接收失败 回调
     * 2.1 correlationData 保存毁掉消息的id及相关信息
     * 2.2 false
     * 2.3 失败原因
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            log.info("发布确认:交换机收到消息id：{}", ObjectUtils.isEmpty(correlationData) ? "" : correlationData.getId());
        } else {
            log.info("发布确认:交换机未收到消息，id为：{},原因：{}", ObjectUtils.isEmpty(correlationData) ? "" : correlationData.getId(), cause);
        }

    }

}
